package com.example.util.sms;

import cn.hutool.captcha.generator.RandomGenerator;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.example.model.SMSModel;
import com.cloopen.rest.sdk.BodyType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
public class SMSUtil {
    @Autowired
    private SMSModel smsModel;


    @Autowired
    private RedisTemplate redisTemplate;

    //短信验证码
    public String generateSMS(String phone) {
        //生成验证码                        翻译: generate 产生;引起
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsModel.getAccountId();
        String accountToken = smsModel.getAuthToken();
//        String accountToken = smsModel.getAuthToken();
        System.out.println("accountSId:" + accountSId);
        System.out.println("accountToken:" + accountToken);
        //管理控制台创建的appid
        String appId = smsModel.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone; //接收短信的手机号码
        String templateId = "1";    //免费开发测试的模版为1
        //4位随机数（采用hutool工具类生成）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        String randomCodeNum = randomGenerator.generate();//4位随机验证码
        Long expireTime = 2l;//验证码有效时间2分钟
        String[] datas = {randomCodeNum, expireTime.toString()};
        //发送短息
        //发送短息
        HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas);
        if("000000".equals(result.get("statusCode"))){
            redisTemplate.opsForValue().set(phone, randomCodeNum, 20, TimeUnit.SECONDS);
            return randomCodeNum;
        }else {
            return null;
        }
    }



    //校验短信验证码
    public boolean validateSMS(String phone, String sms){
        //取出redis中的验证码
        Object redis_code = redisTemplate.opsForValue().get(phone);
        if(Objects.isNull(redis_code)){
            throw new RuntimeException("验证码已过期");
        }
        String  sms_redis = (String) redis_code;
        return sms_redis.equals(sms);
    }

}
